const express = require('express');
let router = express.Router();

const Response = require('../../utils/response');

//日志
const {
    logger
} = require('../../config/logger');

//获取IP
const {
    clientIp
} = require('../../utils/getIp');

//处理node request请求
const request = require('request');

//引入微信配置
const wx = require('../../config/wx');

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const query = require('../../db/userQuery/userQuery')

//处理token
const {
    token_sign,
    token_verify
} = require('../../config/jwt');

//引入时间模块
const sd = require('silly-datetime');
//解析from
const multiparty = require('multiparty')
//存储文件 
const path = require('path');
const fs = require('fs');

//引入微信数据解密
const WXBizDataCrypt = require('../../utils/WXBizDataCrypt')

//登录
router.post('/login', (req, res) => {
    const ip = clientIp(req);
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    if (req.body.code) {
        const encryptedData = req.body.encryptedData;
        const iv = req.body.iv;
        let options = {
            method: 'POST',
            url: 'https://api.weixin.qq.com/sns/jscode2session?',
            formData: {
                appid: wx.appid,
                secret: wx.secret,
                js_code: req.body.code,
                grant_type: 'authorization_code'
            }
        };
        try {
            request(options, (error, response, body) => {
                if (error) { //请求异常时，返回错误信息
                    res.json(Response.error({
                        code: 500,
                        message: "请求微信凭证服务器失败",
                        data: null
                    }))
                    logger().error("请求微信凭证服务器失败: " + error);
                } else {
                    //返回值的字符串转JSON
                    let _data = JSON.parse(body);
                    //解析用户信息
                    const pc = new WXBizDataCrypt(wx.appid, _data.session_key);
                    const userInfo = pc.decryptData(encryptedData, iv);
                    let {
                        nickName,
                        avatarUrl,
                        country,
                        province,
                        city
                    } = userInfo;
                    country == '' ? country = "暂无" : country = country;
                    province == '' ? province = "暂无" : province = province;
                    city == '' ? city = "暂无" : city = city;
                    pool.query(query.user_in, _data.openid, (error, result) => {
                        if (error) {
                            logger().error(`${ip} is logging error: ${error}`);
                            return;
                        }
                        const {
                            count
                        } = JSON.parse(JSON.stringify(result[0]));
                        pool.query(query.insert_login_info, [ip, time], (error, rres) => {
                            if (error) {
                                logger().error(`${ip} is logging error: ${error}`);
                                return;
                            }
                            if (count == 0) {
                                pool.query(query.insert_user, [_data.openid, nickName, avatarUrl, country, province, city], (error, result) => {
                                    if (error) {
                                        logger().error(`${ip} is logging error: ${error}`);
                                        return;
                                    }
                                    const _userId = result.insertId;
                                    pool.query(query.select_openid, _data.openid, (error, result) => {
                                        if (error) {
                                            logger().error(`${ip} is logging error: ${error}`);
                                            return;
                                        }
                                        const token = token_sign({
                                            userId: _userId,
                                            openId: _data.openid,
                                            sessionKey: _data.session_key,
                                            nickName,
                                            role: 0
                                        });
                                        res.json(Response.success("登录成功", {
                                            userId: result.insertId,
                                            sessionKey: _data.session_key,
                                            token,
                                            role: 0
                                        }));
                                        logger().info(`${ip} is logging`);
                                    });
                                });
                            } else {
                                pool.query(query.select_openid, _data.openid, (error, result) => {
                                    if (error) {
                                        logger().error(`${ip} is logging error: ${error}`);
                                        return;
                                    }
                                    const {
                                        id,
                                        role
                                    } = JSON.parse(JSON.stringify(result[0]));
                                    pool.query(query.update_profile, [nickName, avatarUrl, country, province, city, _data.openid], (error, result) => {
                                        if (error) {
                                            logger().error(`${ip} is logging error: ${error}`);
                                            return;
                                        }
                                        const token = token_sign({
                                            userId: id,
                                            openId: _data.openid,
                                            sessionKey: _data.session_key,
                                            role
                                        });
                                        res.json(Response.success("登录成功", {
                                            userId: id,
                                            sessionKey: _data.session_key,
                                            token,
                                            role
                                        }));
                                        logger().info(`${ip} is logging`);
                                    });
                                });
                            }
                        });
                    });
                }
            })
        } catch (e) {
            logger().error(`${ip} is logging error: ${e}`);
            res.json(Response.param_error(null));
        }
    } else {
        logger().error(`${ip} is logging error: 登录参数错误`);
        res.json(Response.param_error(null));
    };
})

//我是业主认证
router.post('/owner', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId,
    } = token_verify(token); //申请者者ID
    const ht = req.protocol; // 获取协议（http或者https）
    const host = req.headers.host; // 获取域名和端口号
    let form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../../../public/images/hoseholdAuth')
    }) // 设置文件存储路径
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    form.parse(req, (err, msg, files) => {
        try {
            const houseId = msg['houseId'][0];
            const name = msg['name'][0];
            const tel = msg['tel'][0];
            const email = msg['email'][0];
            const iamge = files['auth'][0];
            const newPath = form.uploadDir + "/" + iamge.originalFilename
            fs.renameSync(iamge.path, newPath)
            const url = ht + "://" + host + "/images/hoseholdAuth/" + iamge.originalFilename;
            pool.query(query.insert_owner, [userId, houseId, name, tel, email, url, time], (error, result) => {
                if (error) {
                    res.json(Response.error("发起业主认证请求失败", null));
                    logger().error(`业主认证错误: ${error}`);
                } else {
                    res.json(Response.success("发起业主认证请求成功", null));
                }
            });
        } catch (e) {
            res.json(Response.error("发起业主认证请求成功", e));
            logger().error(`业主认证错误: ${e}`);
        }
    })
});

//获取我是业主认证列表
router.get('/houseHoldAuth', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token);
    pool.query(query.select_ownerByuserId, userId, (error, result) => {
        if (error) {
            res.json(Response.error("获取我的业主认证信息失败", null));
            logger().error(`获取我的业主认证列表错误: ${error}`);
            return;
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取我的业主认证信息成功", data));
        }
    });
})

module.exports = router;